package com.tool.completablefuture;

import java.util.concurrent.*;

/**
 * @author niuyicong
 * @date 2024/10/21  18:05:10
 * @description
 */
public class FutureThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 三个任务，目前开启多个异步线程来处理，请问耗时多少
        long startTime = System.currentTimeMillis();

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            // 任务一：假设耗时500ms
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "task1 over";
        });

        threadPool.submit(futureTask1);

        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            // 任务二：假设耗时300ms
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "task2 over";
        });

        threadPool.submit(futureTask2);

        System.out.println(Thread.currentThread().getName() + "获取futureTask1 结果：" + futureTask1.get());
        System.out.println(Thread.currentThread().getName() + "获取futureTask2 结果：" + futureTask2.get());


        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        threadPool.shutdown();

        long endTime = System.currentTimeMillis();

        System.out.println("------costTime：" + (endTime - startTime) + "毫秒");
        System.out.println(Thread.currentThread().getName() + "\t ------end");
    }

    public static void m1(){
        // 三个任务，目前只有一个线程main来处理，请问耗时是多少
        long startTime = System.currentTimeMillis();

        try {TimeUnit.MILLISECONDS.sleep(500);}catch (InterruptedException e){e.printStackTrace();}
        try {TimeUnit.MILLISECONDS.sleep(300);}catch (InterruptedException e){e.printStackTrace();}
        try {TimeUnit.MILLISECONDS.sleep(300);}catch (InterruptedException e){e.printStackTrace();}

        long endTime = System.currentTimeMillis();
        System.out.println("------ costTime：" + (endTime - startTime) + " 毫秒");
        System.out.println(Thread.currentThread().getName() + "\t ------end");
    }
}
